import os
import shutil
import argparse


def link_config(name):
    config_folder_path = os.path.expanduser(f"~/.local/share/{name}")
    dotfiles_path = os.path.expanduser("~/dotfiles")

    # 如果符号链接存在，删除符号链接
    if os.path.islink(config_folder_path):
        try:
            os.unlink(config_folder_path)
            print(f"Symbolic link {config_folder_path} successfully removed.")
        except OSError as e:
            print(f"Failed to remove symbolic link {config_folder_path}: {e}")

    # 如果目录存在，删除目录
    elif os.path.exists(config_folder_path) and os.path.isdir(config_folder_path):
        try:
            shutil.rmtree(config_folder_path)
            print(f"Directory {config_folder_path} successfully removed.")
        except OSError as e:
            print(f"Failed to remove directory {config_folder_path}: {e}")

    # 创建符号链接
    try:
        os.symlink(os.path.join(dotfiles_path, name), config_folder_path)
        print(f"Symbolic link for {name} successfully set.")
    except OSError as e:
        print(f"Failed: {e}")


def main():
    parser = argparse.ArgumentParser(description="管理配置文件的脚本")
    parser.add_argument(
        "names", nargs="*", default=[], help="要处理的配置文件夹名称列表，默认为全部"
    )

    args = parser.parse_args()

    if not args.names:
        args.names = ["konsole"]

    for name in args.names:
        link_config(name)


if __name__ == "__main__":
    main()
